<template>
  <div class="tags-page transition-colors duration-300">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">标签管理</h1>
        <p class="page-description">管理博客文章的标签分类</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateModal" class="create-btn">
          <el-icon><Plus /></el-icon>
          新建标签
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card
        class="stat-card dark:bg-gray-800 dark:border-gray-700"
        shadow="hover"
      >
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Collection /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalTags }}</div>
            <div class="stat-label">总标签数</div>
          </div>
        </div>
      </el-card>

      <el-card
        class="stat-card dark:bg-gray-800 dark:border-gray-700"
        shadow="hover"
      >
        <div class="stat-content">
          <div class="stat-icon active">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ activeTags }}</div>
            <div class="stat-label">活跃标签</div>
          </div>
        </div>
      </el-card>

      <el-card
        class="stat-card dark:bg-gray-800 dark:border-gray-700"
        shadow="hover"
      >
        <div class="stat-content">
          <div class="stat-icon inactive">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ inactiveTags }}</div>
            <div class="stat-label">未使用标签</div>
          </div>
        </div>
      </el-card>

      <el-card
        class="stat-card dark:bg-gray-800 dark:border-gray-700"
        shadow="hover"
      >
        <div class="stat-content">
          <div class="stat-icon posts">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalPosts }}</div>
            <div class="stat-label">总文章数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <el-card
      class="search-card dark:bg-gray-800 dark:border-gray-700"
      shadow="never"
    >
      <div class="search-container">
        <div class="search-filters">
          <el-input
            v-model="searchText"
            placeholder="搜索标签名称或别名..."
            clearable
            style="width: 300px"
            @input="handleSearch"
            class="dark:bg-gray-700 dark:border-gray-600"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            clearable
            style="width: 150px"
            @change="handleFilter"
            class="dark:bg-gray-700 dark:border-gray-600"
          >
            <el-option label="活跃" value="active" />
            <el-option label="未使用" value="inactive" />
          </el-select>

          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 标签列表 -->
    <el-card
      class="table-card dark:bg-gray-800 dark:border-gray-700"
      shadow="never"
    >
      <el-table
        :data="filteredTags"
        :loading="loading"
        style="width: 100%"
        v-loading="loading"
        class="dark:text-gray-200"
        :row-class-name="tableRowClassName"
      >
        <el-table-column label="标签名称">
          <template #default="{ row }">
            <div class="tag-name">
              <el-tag :color="getTagColor(row.color)" effect="dark">
                {{ row.name }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="slug" label="别名" width="120" />

        <el-table-column prop="postCount" label="文章数量" align="center">
          <template #default="{ row }">
            <span
              :class="['post-count', row.postCount > 0 ? 'active' : 'inactive']"
            >
              {{ row.postCount }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.postCount > 0 ? 'success' : 'info'">
              {{ row.postCount > 0 ? "活跃" : "未使用" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" link size="small" @click="editTag(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-popconfirm
                title="确定要删除这个标签吗？"
                @confirm="deleteTag(row.id)"
              >
                <template #reference>
                  <el-button type="danger" link size="small">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑标签模态框 -->
    <el-dialog
      v-model="modalVisible"
      :title="editingTag ? '编辑标签' : '新建标签'"
      width="600px"
      :before-close="handleCancel"
      class="dark:bg-gray-800"
    >
      <el-form
        :model="tagForm"
        :rules="rules"
        ref="formRef"
        label-width="80px"
        class="dark:text-gray-200"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签名称" prop="name">
              <el-input
                v-model="tagForm.name"
                placeholder="请输入标签名称"
                maxlength="20"
                show-word-limit
                class="dark:bg-gray-700 dark:border-gray-600"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签别名" prop="slug">
              <el-input
                v-model="tagForm.slug"
                placeholder="用于URL，如：javascript"
                maxlength="30"
                show-word-limit
                class="dark:bg-gray-700 dark:border-gray-600"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签颜色" prop="color">
              <div class="color-picker-container">
                <el-select
                  v-model="tagForm.color"
                  placeholder="选择标签颜色"
                  style="width: 200px"
                  class="dark:bg-gray-700 dark:border-gray-600"
                >
                  <el-option label="蓝色" value="#409EFF" />
                  <el-option label="绿色" value="#67C23A" />
                  <el-option label="橙色" value="#E6A23C" />
                  <el-option label="红色" value="#F56C6C" />
                  <el-option label="紫色" value="#B37FEB" />
                  <el-option label="青色" value="#36CFC9" />
                </el-select>
                <el-input
                  v-model="tagForm.color"
                  placeholder="#409EFF"
                  style="width: 120px; margin-left: 10px"
                  class="dark:bg-gray-700 dark:border-gray-600"
                />
                <div
                  class="color-preview"
                  :style="{ backgroundColor: tagForm.color || '#409EFF' }"
                ></div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ editingTag ? "更新" : "创建" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { AdminTag } from "~/types/admin";

// 图标导入
const {
  Plus,
  Collection,
  Check,
  Clock,
  Document,
  Search,
  Refresh,
  Edit,
  Delete,
} = await import("@element-plus/icons-vue");

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const submitting = ref(false);
const editingTag = ref<AdminTag | null>(null);
const searchText = ref("");
const statusFilter = ref<string>();
const formRef = ref();

// 标签表单
const tagForm = ref({
  name: "",
  slug: "",
  color: "blue",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    {
      min: 1,
      max: 20,
      message: "标签名称长度在 1 到 20 个字符",
      trigger: "blur",
    },
  ],
  slug: [
    { required: true, message: "请输入标签别名", trigger: "blur" },
    {
      min: 1,
      max: 30,
      message: "标签别名长度在 1 到 30 个字符",
      trigger: "blur",
    },
    {
      pattern: /^[a-z0-9-]+$/,
      message: "标签别名只能包含小写字母、数字和连字符",
      trigger: "blur",
    },
  ],
};

// 标签数据
const tags = ref<AdminTag[]>([]);
const totalPostsCount = ref(0);

// 加载标签数据
const loadTags = async () => {
  try {
    loading.value = true;
    const { success, data } = await $fetch<{
      success: boolean;
      data: AdminTag[];
      message: string;
    }>("/api/admin/tags");
    if (success) {
      tags.value = data || [];
    }

    // 计算总文章数
    totalPostsCount.value = tags.value.reduce(
      (sum, tag) => sum + tag.postCount,
      0
    );
  } catch (error) {
    console.error("加载标签失败:", error);
    ElMessage.error("加载标签失败");
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadTags();
});

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 计算属性
const totalTags = computed(() => tags.value.length);
const activeTags = computed(
  () => tags.value.filter((tag) => tag.postCount > 0).length
);
const inactiveTags = computed(
  () => tags.value.filter((tag) => tag.postCount === 0).length
);
const totalPosts = computed(() => totalPostsCount.value);

// 计算属性：过滤后的标签
const filteredTags = computed(() => {
  let result = tags.value;

  if (searchText.value) {
    const search = searchText.value.toLowerCase();
    result = result.filter(
      (tag) =>
        tag.name.toLowerCase().includes(search) ||
        tag.slug.toLowerCase().includes(search)
    );
  }

  if (statusFilter.value) {
    result = result.filter((tag) => {
      if (statusFilter.value === "active") return tag.postCount > 0;
      if (statusFilter.value === "inactive") return tag.postCount === 0;
      return true;
    });
  }

  pagination.value.total = result.length;

  // 分页处理
  const start = (pagination.value.current - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return result.slice(start, end);
});

// 方法
const getTagColor = (color: string) => {
  // 如果是颜色代码（#开头的），直接返回
  if (color.startsWith("#")) {
    return color;
  }

  // 如果是颜色名称，映射到对应颜色
  const colorMap: Record<string, string> = {
    blue: "#409EFF",
    green: "#67C23A",
    orange: "#E6A23C",
    red: "#F56C6C",
    purple: "#B37FEB",
    cyan: "#36CFC9",
  };
  return colorMap[color] || "#409EFF";
};

const showCreateModal = () => {
  editingTag.value = null;
  tagForm.value = {
    name: "",
    slug: "",
    color: "blue",
  };
  modalVisible.value = true;
};

const editTag = (tag: AdminTag) => {
  editingTag.value = tag;
  // 确保颜色值是十六进制格式
  let color = tag.color || "#409EFF";
  if (!color.startsWith("#")) {
    // 如果是颜色名称，转换为对应的十六进制值
    const colorMap: Record<string, string> = {
      blue: "#409EFF",
      green: "#67C23A",
      orange: "#E6A23C",
      red: "#F56C6C",
      purple: "#B37FEB",
      cyan: "#36CFC9",
    };
    color = colorMap[color] || "#409EFF";
  }

  tagForm.value = {
    name: tag.name,
    slug: tag.slug,
    color: color,
  };
  modalVisible.value = true;
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;

    if (editingTag.value) {
      // 编辑标签
      const tagId = editingTag.value.id;
      const { success, message } = await $fetch(`/api/admin/tags/${tagId}`, {
        method: "PUT",
        body: {
          name: tagForm.value.name,
          slug: tagForm.value.slug,
          color: tagForm.value.color,
        },
      });
      if (success) {
        ElMessage.success("标签更新成功！");
      } else {
        ElMessage.error(message);
      }
    } else {
      // 新建标签
      const { success, message } = await $fetch("/api/admin/tags", {
        method: "POST",
        body: {
          name: tagForm.value.name,
          slug: tagForm.value.slug,
          color: tagForm.value.color,
        },
      });
      if (success) {
        ElMessage.success("标签创建成功！");
      } else {
        ElMessage.error(message);
      }
    }

    modalVisible.value = false;
    // 重新加载数据
    await loadTags();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error(error instanceof Error ? error.message : "操作失败");
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  modalVisible.value = false;
  formRef.value?.resetFields();
};

const deleteTag = async (id: string) => {
  try {
    const { success, message } = await $fetch(`/api/admin/tags/${id}`, {
      method: "DELETE",
    });
    if (success) {
      ElMessage.success("标签删除成功！");
    } else {
      ElMessage.error(message);
    }
    // 重新加载数据
    await loadTags();
  } catch (error) {
    console.error("删除标签失败:", error);
    ElMessage.error(error instanceof Error ? error.message : "删除失败");
  }
};

const handleSearch = () => {
  pagination.value.current = 1;
};

const handleFilter = () => {
  pagination.value.current = 1;
};

const resetFilters = () => {
  searchText.value = "";
  statusFilter.value = undefined;
  pagination.value.current = 1;
};

const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};

const handleCurrentChange = (current: number) => {
  pagination.value.current = current;
};

// Element Plus表格行样式
const tableRowClassName = () => {
  return "dark:hover:bg-gray-700";
};

// 页面元数据
useHead({
  title: "标签管理 - 博客管理系统",
});
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  animation: fadeInDown 0.6s ease-out;
}

.header-content h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.dark .header-content h1 {
  background: linear-gradient(135deg, #a5b4fc 0%, #c084fc 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-content p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.dark .header-content p {
  color: #9ca3af;
}

.create-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
  animation: fadeInUp 0.6s ease-out 0.2s both;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.dark .stat-card {
  background: rgba(31, 41, 55, 0.95);
}

.dark .stat-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
}

.stat-icon.inactive {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
}

.stat-icon.posts {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  line-height: 1;
}

.dark .stat-value {
  color: #f3f4f6;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.dark .stat-label {
  color: #9ca3af;
}

/* 搜索卡片 */
.search-card {
  border-radius: 12px;
  margin-bottom: 24px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  animation: fadeInUp 0.6s ease-out 0.4s both;
}

.dark .search-card {
  background: rgba(31, 41, 55, 0.95);
}

.search-container {
  padding: 8px 0;
}

.search-filters {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 表格卡片 */
.table-card {
  border-radius: 12px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  animation: fadeInUp 0.6s ease-out 0.6s both;
}

.dark .table-card {
  background: rgba(31, 41, 55, 0.95);
}

.tag-name {
  display: flex;
  align-items: center;
}

.post-count {
  font-weight: 600;
  font-size: 16px;
}

.post-count.active {
  color: #4caf50;
}

.dark .post-count.active {
  color: #34d399;
}

.post-count.inactive {
  color: #999;
}

.dark .post-count.inactive {
  color: #6b7280;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.dark .pagination-container :deep(.el-pagination) {
  --el-pagination-button-disabled-bg-color: #374151;
  --el-pagination-bg-color: #374151;
  --el-pagination-disabled-color: #6b7280;
  --el-pagination-button-color: #d1d5db;
  --el-pagination-hover-color: #60a5fa;
}

/* 动画效果 */
@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Element Plus组件暗黑模式样式 */
:deep(.dark .el-table) {
  --el-table-bg-color: transparent;
  --el-table-header-bg-color: rgba(55, 65, 81, 0.5);
  --el-table-row-hover-bg-color: rgba(75, 85, 99, 0.3);
  --el-table-text-color: #f3f4f6;
  --el-table-header-text-color: #d1d5db;
  --el-table-border-color: #374151;
}

:deep(.dark .el-table__body-wrapper) {
  background-color: transparent;
}

:deep(.dark .el-pagination) {
  --el-pagination-button-bg-color: #374151;
  --el-pagination-hover-color: #4b5563;
  --el-pagination-text-color: #d1d5db;
}

:deep(.dark .el-input) {
  --el-input-bg-color: #374151;
  --el-input-text-color: #f3f4f6;
  --el-input-border-color: #4b5563;
  --el-input-hover-border-color: #6b7280;
  --el-input-focus-border-color: #60a5fa;
}

:deep(.dark .el-input__wrapper) {
  background-color: #374151;
  border-color: #4b5563;
}

:deep(.dark .el-input__wrapper:hover) {
  border-color: #6b7280;
}

:deep(.dark .el-input__wrapper.is-focus) {
  border-color: #60a5fa;
  box-shadow: 0 0 0 1px rgba(96, 165, 250, 0.2);
}

:deep(.dark .el-select) {
  --el-select-input-focus-border-color: #60a5fa;
}

:deep(.dark .el-select__wrapper) {
  background-color: #374151;
  border-color: #4b5563;
}

:deep(.dark .el-select__wrapper:hover) {
  border-color: #6b7280;
}

:deep(.dark .el-select__wrapper.is-focus) {
  border-color: #60a5fa;
  box-shadow: 0 0 0 1px rgba(96, 165, 250, 0.2);
}

:deep(.dark .el-textarea__inner) {
  background-color: #374151;
  border-color: #4b5563;
  color: #f3f4f6;
}

:deep(.dark .el-textarea__inner:hover) {
  border-color: #6b7280;
}

:deep(.dark .el-textarea__inner:focus) {
  border-color: #60a5fa;
  box-shadow: 0 0 0 1px rgba(96, 165, 250, 0.2);
}

:deep(.dark .el-form-item__label) {
  color: #d1d5db;
}

:deep(.dark .el-dialog) {
  background-color: #1f2937;
  border: 1px solid #374151;
}

:deep(.dark .el-dialog__header) {
  border-bottom: 1px solid #374151;
  color: #f3f4f6;
}

:deep(.dark .el-dialog__title) {
  color: #f3f4f6;
}

:deep(.dark .el-button) {
  border-color: #4b5563;
}

:deep(.dark .el-button--default) {
  background-color: #374151;
  border-color: #4b5563;
  color: #d1d5db;
}

:deep(.dark .el-button--default:hover) {
  background-color: #4b5563;
  border-color: #6b7280;
}

:deep(.dark .el-button--primary) {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

:deep(.dark .el-button--primary:hover) {
  background-color: #2563eb;
  border-color: #2563eb;
}

:deep(.dark .el-button--danger) {
  background-color: #ef4444;
  border-color: #ef4444;
}

:deep(.dark .el-button--danger:hover) {
  background-color: #dc2626;
  border-color: #dc2626;
}

:deep(.dark .el-icon) {
  color: inherit;
}

:deep(.dark .el-tag) {
  background-color: #374151;
  border-color: #4b5563;
  color: #d1d5db;
}

:deep(.dark .el-tag--success) {
  background-color: rgba(34, 197, 94, 0.2);
  border-color: #22c55e;
  color: #86efac;
}

:deep(.dark .el-tag--info) {
  background-color: rgba(156, 163, 175, 0.2);
  border-color: #9ca3af;
  color: #d1d5db;
}

:deep(.dark .el-popconfirm) {
  background-color: #374151;
  border: 1px solid #4b5563;
  color: #d1d5db;
}

:deep(.dark .el-popper) {
  background-color: #374151;
  border: 1px solid #4b5563;
  color: #d1d5db;
}

:deep(.dark .el-form-item__error) {
  color: #f87171;
}

/* 颜色选择器样式 */
.color-picker-container {
  display: flex;
  align-items: center;
}

.color-preview {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  margin-left: 10px;
  border: 1px solid #dcdfe6;
  flex-shrink: 0;
}

.dark .color-preview {
  border-color: #4b5563;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tags-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .search-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .search-filters :deep(.el-input),
  .search-filters :deep(.el-select) {
    width: 100% !important;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 480px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
  }

  .stat-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }
}
</style>
